#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: generate_xmind.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 生成xmind文件
"""

import json
import zipfile
import os
import uuid
import time
from xml.etree import ElementTree as ET
import shutil

def json_to_xmind(json_data, output_path="output.xmind"):
    # 创建临时目录
    temp_dir = "ccs_xmind_test"
    os.makedirs(temp_dir, exist_ok=True)

    # 创建 content.xml（用于：XML格式存储节点/样式）
    # 注册命名空间
    ET.register_namespace('', "urn:xmind:xmap:xmlns:content:2.0")
    ET.register_namespace('fo', "http://www.w3.org/1999/XSL/Format")
    ET.register_namespace('svg', "http://www.w3.org/2000/svg")
    ET.register_namespace('xhtml', "http://www.w3.org/1999/xhtml")
    ET.register_namespace('xlink', "http://www.w3.org/1999/xlink")
    
    # 创建根元素并添加属性
    root = ET.Element("{urn:xmind:xmap:xmlns:content:2.0}xmap-content", 
                      **{"modified-by": "ccs", "timestamp": "1756006801814", "version": "2.0"})
    
    # 创建sheet元素并添加属性
    sheet = ET.SubElement(root, "{urn:xmind:xmap:xmlns:content:2.0}sheet", 
                          id=str(uuid.uuid4()),
                          **{"structure-class": "org.xmind.ui.logic.right", 
                             "modified-by": "ccs", 
                             "timestamp": "1756006801814"})
    
    # 处理JSON数据，如果是一个列表，则取第一个元素
    if isinstance(json_data, list):
        json_data = json_data[0]
    
    # 创建topic元素并添加属性
    topic = ET.SubElement(sheet, "{urn:xmind:xmap:xmlns:content:2.0}topic", id="root",
                          timestamp="1756006801814", **{"modified-by": "chenchangsong", "structure-class": "org.xmind.ui.logic.right"})
    title = ET.SubElement(topic, "{urn:xmind:xmap:xmlns:content:2.0}title")
    title.text = json_data["title"]

    # 递归添加主题
    def add_topics(parent, topics):
        for topic_data in topics:
            child = ET.SubElement(parent, "{urn:xmind:xmap:xmlns:content:2.0}topic",
                                  id=f"topic_{uuid.uuid4()}",
                                  timestamp=str(int(time.time() * 1000)))

            # 标题
            child_title = ET.SubElement(child, "{urn:xmind:xmap:xmlns:content:2.0}title")
            child_title.text = topic_data["title"]

            # 子主题
            if "children" in topic_data and topic_data["children"]:
                children = ET.SubElement(child, "{urn:xmind:xmap:xmlns:content:2.0}children")
                topics_elem = ET.SubElement(children, "{urn:xmind:xmap:xmlns:content:2.0}topics",
                                            type="attached")
                add_topics(topics_elem, topic_data["children"])

    # 构建主题结构
    if "children" in json_data and json_data["children"]:
        children = ET.SubElement(topic, "{urn:xmind:xmap:xmlns:content:2.0}children")
        topics_elem = ET.SubElement(children, "{urn:xmind:xmap:xmlns:content:2.0}topics",
                                    type="attached")
        add_topics(topics_elem, json_data["children"])

    # 创建ElementTree并写入文件
    tree = ET.ElementTree(root)
    content_path = os.path.join(temp_dir, "content.xml")
    tree.write(content_path, encoding="utf-8", xml_declaration=True)

    # 创建META-INF目录
    meta_inf_dir = os.path.join(temp_dir, "META-INF")
    os.makedirs(meta_inf_dir, exist_ok=True)

    # 创建manifest.xml
    """
    <manifest xmlns="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
        <file-entry full-path="content.xml" media-type="text/xml"/>
    </manifest>
    """
    ET.register_namespace('', "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0")
    manifest = ET.Element("{urn:oasis:names:tc:opendocument:xmlns:manifest:1.0}manifest")
    file_entry = ET.SubElement(manifest, "{urn:oasis:names:tc:opendocument:xmlns:manifest:1.0}file-entry")
    file_entry.set("full-path", "content.xml")
    file_entry.set("media-type", "text/xml")

    manifest_tree = ET.ElementTree(manifest)
    manifest_path = os.path.join(meta_inf_dir, "manifest.xml")
    manifest_tree.write(manifest_path, encoding="utf-8", xml_declaration=True)

    # 创建XMind文件
    with zipfile.ZipFile(output_path, "w") as zf:
        zf.write(content_path, "content.xml")
        zf.write(manifest_path, "META-INF/manifest.xml")
        # zf.writestr("Thumbnails/thumbnail.png", b"") # 缩略图目录 存储思维导图的预览图（通常是 thumbnail.png），用于文件管理器快速预览。
        # zf.writestr("Comments/comments.xml", b"<comments/>") # 存储用户添加的批注/评论

    # 清理临时文件
    shutil.rmtree(temp_dir)

    print(f"成功生成XMind文件: {output_path}")


if __name__ == "__main__":
    sample_json = {
    "title": "中心分支",
    "children": [
        {
            "title": "分支1",
            "children": [
                {
                    "title": "分支1-1",
                    "children": [
                        {
                            "title": "分支1-1-1",
                            "children": [
                                {
                                    "title": "分支1-1-1-1",
                                    "children": [
                                        {
                                            "title": "分支1-1-1-1-1"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "title": "分支2",
            "children": [
                {
                    "title": "分支2-1",
                    "children": [
                        {
                            "title": "分支2-1-1",
                            "children": [
                                {
                                    "title": "分支2-1-1-1",
                                    "children": [
                                        {
                                            "title": "分支2-1-1-1-1",
                                            "children": [
                                                {
                                                    "title": "分支2-1-1-1-1-1"
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    "title": "分支2-2",
                    "children": [
                        {
                            "title": "分支2-2-1",
                            "children": [
                                {
                                    "title": "分支2-2-1-1",
                                    "children": [
                                        {
                                            "title": "分支2-2-1-1-1",
                                            "children": [
                                                {
                                                    "title": "分支2-2-1-1-1-1"
                                                }
                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            "title": "分支3",
            "children": [
                {
                    "title": "分支3-1",
                    "children": [
                        {
                            "title": "分支3-1-1",
                            "children": [
                                {
                                    "title": "分支3-1-1-1",
                                    "children": [
                                        {
                                            "title": "分支3-1-1-1-1",
                                            "children": [
                                                {
                                                    "title": "分支3-1-1-1-1-1"
                                                }
                                            ]
                                        },
                                        {
                                            "title": "分支3-1-1-1-2",
                                            "children": [
                                                {
                                                    "title": "分支3-1-1-1-2-1",
                                                    "children": [
                                                        {
                                                            "title": "分支3-1-1-1-2-1-1"
                                                        }
                                                    ]
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    "title": "分支3-1-1-2",
                                    "children": [
                                        {
                                            "title": "分支3-1-1-2-1"
                                        },
                                        {
                                            "title": "分支3-1-1-2-2"
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "title": "分支3-1-2",
                            "children": [
                                {
                                    "title": "分支3-1-2-1"
                                },
                                {
                                    "title": "分支3-1-2-2"
                                }
                            ]
                        }
                    ]
                },
                {
                    "title": "分支3-2",
                    "children": [
                        {
                            "title": "分支3-2-1"
                        },
                        {
                            "title": "分支3-2-2"
                        }
                    ]
                },
                {
                    "title": "分支3-3",
                    "children": []
                }
            ]
        }
    ]
}
    # 构建配置文件的路径
    from ui_code.common_ui import get_project_root
    json_file_path = get_project_root() / "files" / "手动导入_2025-09-14_21-33-51_补充后.json"
    json_file_data = json.load(open(json_file_path, 'r', encoding='utf-8'))
    # 保存XMind文件的路径
    save_xmind_path = get_project_root() / "files" / "手动导入_2025-09-14_21-33-51_补充后1.xmind"
    
    # 通过json文件生成XMind文件
    # json_to_xmind(sample_json, save_xmind_path)

    # 通过文件生成xmind
    json_to_xmind(json_file_data, save_xmind_path)